package web

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"riceguess_backend/internal/service"
)

type AIHandler struct {
	svc service.AIService
}

func NewAIHandler(svc service.AIService) *AIHandler {
	return &AIHandler{
		svc: svc,
	}
}

// GetTitle 获取题面
func (h *AIHandler) GetTitle(ctx *gin.Context) {
	answer, err := h.svc.GetTitle(ctx)
	if err != nil {
		ctx.JSON(http.StatusOK, Result[string]{
			Code: 5,
			Msg:  "系统错误",
		})
		// TODO 记录日志
		return
	}
	type Resp struct {
		Id    string `json:"id"`
		Title string `json:"title"`
	}
	ctx.JSON(http.StatusOK, Result[Resp]{
		Code: 0,
		Data: Resp{
			Id:    answer.Id,
			Title: answer.Title,
		},
		Msg: "OK",
	})
}

// SendQuestion 发送问题
func (h *AIHandler) SendQuestion(ctx *gin.Context) {
	type Req struct {
		Id       string `json:"id"`
		Question string `json:"question"`
	}
	var req Req
	if err := ctx.Bind(&req); err != nil {
		ctx.JSON(http.StatusOK, Result[string]{
			Code: 5,
			Msg:  "系统错误",
		})
		return
	}
	resp, err := h.svc.SendQuestion(ctx, req.Id, req.Question)
	if err != nil {
		ctx.JSON(http.StatusOK, Result[string]{
			Code: 5,
			Msg:  "系统错误",
		})
		return
	}
	ctx.JSON(http.StatusOK, Result[string]{
		Code: 0,
		Data: resp,
		Msg:  "OK",
	})
}

// ReduceTruth 还原真相
func (h *AIHandler) ReduceTruth(ctx *gin.Context) {
	type Req struct {
		Id    string `json:"id"`
		Guess string `json:"guess"`
	}
	var req Req
	if err := ctx.Bind(&req); err != nil {
		ctx.JSON(http.StatusOK, Result[string]{
			Code: 5,
			Msg:  "系统错误",
		})
		return
	}
	resp, err := h.svc.ReduceTruth(ctx, req.Id, req.Guess)
	if err != nil {
		ctx.JSON(http.StatusOK, Result[string]{
			Code: 5,
			Msg:  "系统错误",
		})
		return
	}
	ctx.JSON(http.StatusOK, Result[bool]{
		Code: 0,
		Data: resp,
		Msg:  "OK",
	})
}

func (h *AIHandler) RegisterRoutes(server *gin.Engine) {
	ag := server.Group("/ai")
	ag.GET("/title", h.GetTitle)
	ag.POST("/question", h.SendQuestion)
	ag.POST("/reduce", h.ReduceTruth)
}
